package com.vanke.agent;

//
// Copyright (c) 2014, 保留所有权利。
//
// ADataSource.java
//
// 作    者：王红燕
// 当前版本：1.0
// 2014 上午8:54:57
//
// 
//

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

import com.vanke.agent.common.Util;
import com.vanke.agent.sync.AgentContext;

/**
 *
 */
public class ADataSource {
	public static final String SCHEMA_MY = "my";
	public static final String SCHEMA_BIZ = "biz";
	public static final String SCHEMA_EM = "em";

	static String myUrl;
	static String myUser;
	static String myPwd;

	static String bizUrl;
	static String bizUser;
	static String bizPwd;
	
	static String emUrl;
	static String emUser;
	static String emPwd;

	static {
		try {
			Properties p = new Properties();
			p.load(new FileInputStream("db.ini"));

			myUrl = p.getProperty("my.url");
			myUser = p.getProperty("my.user");
			myPwd = p.getProperty("my.pwd");

			bizUrl = p.getProperty("biz.url");
			bizUser = p.getProperty("biz.user");
			bizPwd = p.getProperty("biz.pwd");
			
			emUrl = p.getProperty("em.url");
			emUser = p.getProperty("em.user");
			emPwd = p.getProperty("em.pwd");
			
			Class.forName("org.gjt.mm.mysql.Driver");
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
		} catch (Exception e) {
			e.printStackTrace();
			AgentContext.exit(Util.formatStackTrace(e));
		}
	}

	// 获取数据库连接
	public static Connection getConnection(String schema) {
		try {
			if (SCHEMA_MY.equals(schema)) {
				return DriverManager.getConnection(myUrl, myUser, myPwd);
			}
			if (SCHEMA_BIZ.equals(schema)) {
				return DriverManager.getConnection(bizUrl, bizUser, bizPwd);
			}
			if (SCHEMA_EM.equals(schema)) {
				return DriverManager.getConnection(emUrl, emUser, emPwd);
			}
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	// 关闭连接
	public static void close(Connection conn) {
		if (conn != null) {
			try {
				conn.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	// 关闭会话
	public static void close(Statement stm) {
		if (stm != null) {
			try {
				stm.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	// 关闭结果集
	public static void close(ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	// 关闭数据库资源
	public static void close(ResultSet rs, Statement stmt, Connection conn) {
		close(rs);
		close(stmt);
		close(conn);
	}

}
